# 导入llama_index核心模块中的VectorStoreIndex、Document和StorageContext类
from llama_index.core import VectorStoreIndex, Document, StorageContext
from llama_index.vector_stores.weaviate import WeaviateVectorStore

# 用于连接云服务
import weaviate

# 用于API密钥认证
from weaviate.classes.init import Auth

weaviate_url = "ihszbqsrtlo71ntrbjtclg.c0.asia-southeast1.gcp.weaviate.cloud"

weaviate_api_key = "b0dLTEQ4eVNoRlhiM1JrUF8weVFwdGlGYm5qeTZNaG9FMWFmeTZGTXp0ZFVKMVgrL203OHp4eTVQZktjPV92MjAw"

client = weaviate.connect_to_weaviate_cloud(
    cluster_url=weaviate_url, auth_credentials=Auth.api_key(weaviate_api_key)
)
# 创建WeaviateVectorStore对象，指定索引名称和客户端连接
vector_store = WeaviateVectorStore(weaviate_client=client, index_name="LlamaIndexDemo")
# 创建存储上下文，绑定向量存储
storage_context = StorageContext.from_defaults(vector_store=vector_store)

# 构建示例文本列表
sample_texts = [
    "Weaviate是一个开源的向量数据库，支持多种数据类型。",
    "Weaviate提供了GraphQL API，便于集成和查询。",
    "Weaviate支持语义搜索和结构化数据查询。",
]

documents = [Document(text=text) for text in sample_texts]
index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context, show_progress=True
)

# 获取查询引擎对象
query_engine = index.as_query_engine()
# 使用查询引擎进行问题检索
response = query_engine.query("Weaviate的优势是什么？")
# 打印查询结果
print(f"查询结果: {response}")
client.close()
